package com.example.wenqujingdian.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.wenqujingdian.R;
import com.example.wenqujingdian.adapter.CustomerShowAdapter;
import com.example.wenqujingdian.api.Contants;
import com.example.wenqujingdian.api.JsonDataManager;
import com.example.wenqujingdian.bean.FileBean;
import com.example.wenqujingdian.utils.ToastUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Create by kxliu on 2020/6/11
 */
public class CustomerShowActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener, View.OnClickListener {
    private ProgressDialog progressDialog;
    //    private ListView lv_menu;
    private RecyclerView recyclerView;
    private RelativeLayout mNoUsbLayout;
//    private MenuAdapter menuAdapter;
    //    private List<String> menuList;
    private ArrayList<FileBean> mData = new ArrayList<>();
    private CustomerShowAdapter mAdapter;
    private int type = 0;
    private List<FileBean> playVideoList = new ArrayList<>();
    private boolean isLand;

    private TextView image;
    private TextView video;
    private TextView file;

    private GridLayoutManager manager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_show);
        initView();
        checkPermission();
    }

    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            List<String> applyPermissionList = new ArrayList<>();
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                applyPermissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                applyPermissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            if (applyPermissionList.size() == 0) {
                Contants.SPICIFYPATH = JsonDataManager.getInstance().getSpecificPath();
//                initView();
                initData(Contants.IMAGE, type);
            } else {
                //请求所缺少的权限。
                String[] requestPermissions = new String[applyPermissionList.size()];
                applyPermissionList.toArray(requestPermissions);
                requestPermissions(requestPermissions, Contants.PERMISSION_STORAGE);
            }
        } else {
            Contants.SPICIFYPATH = JsonDataManager.getInstance().getSpecificPath();
//            initView();
            initData(Contants.IMAGE, type);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == Contants.PERMISSION_STORAGE) {
            if (isAllPermissionsGranted(grantResults)) {
                Contants.SPICIFYPATH = JsonDataManager.getInstance().getSpecificPath();
                initData(Contants.IMAGE, type);
            } else {
                ToastUtil.show("读写权限被拒绝");
            }
        }
    }

    /**
     * 所有权限是否申请成功
     *
     * @param grantResults 权限获得结果的数组
     * @return ture:成功  false:失败
     */
    private boolean isAllPermissionsGranted(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                //如果有一个权限返回的是失败,返回false
                return false;
            }
        }
        return true;
    }


    private void initData(String file, final int type) {
        showDialog();
        JsonDataManager.getInstance().getCustomerDate(file, type,
                new JsonDataManager.OnLocalListDataListener<FileBean>() {
                    @Override
                    public void onSuccess(List<FileBean> data) {
                        progressDialog.dismiss();
                        mData.clear();
                        if (type == 2) {
                            manager.setSpanCount(1);
                        } else {
                            if (isLand) {
                                manager.setSpanCount(5);
                            } else {
                                manager.setSpanCount(3);
                            }
                        }
                        mData.addAll(data);
                        mAdapter.notifyDataSetChanged();

                    }

                    @Override
                    public void onFail(String info) {
                        progressDialog.dismiss();
                        mNoUsbLayout = findViewById(R.id.no_usb_layout);
                        mNoUsbLayout.setVisibility(View.VISIBLE);
                    }
                });
    }

    private void initView() {
        progressDialog = new ProgressDialog(this);
//        lv_menu = findViewById(R.id.lv_menu);
        image = findViewById(R.id.tv_image);
        video = findViewById(R.id.tv_video);
        file = findViewById(R.id.tv_file);
        image.setOnClickListener(this);
        video.setOnClickListener(this);
        file.setOnClickListener(this);
        recyclerView = findViewById(R.id.lv_home);
        mNoUsbLayout = findViewById(R.id.no_usb_layout);
        Toolbar toolbar = (Toolbar) findViewById(R.id.tb);
        ((TextView) toolbar.findViewById(R.id.title)).setText("风采展示");
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

//        menuList = new ArrayList<>();

//        menuList.add("图片");
//        menuList.add("视频");
//        menuList.add("文档");
        image.setBackgroundColor(Color.WHITE);
        image.setTextColor(getResources().getColor(R.color.green));
//        menuAdapter = new MenuAdapter(this, menuList);
//        lv_menu.setAdapter(menuAdapter);

//        lv_menu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                menuAdapter.setSelectItem(position);
//                menuAdapter.notifyDataSetInvalidated();
//                if (position == type) return;
//                switch (position) {
//                    case 0:
//                        type = 0;
//                        initData(Contants.IMAGE, type);
//                        break;
//                    case 1:
//                        type = 1;
//                        initData(Contants.VIDEO, type);
//                        break;
//                    case 2:
//                        type = 2;
//                        initData(Contants.FILE, type);
//                        break;
//                }
//            }
//        });

        if (findViewById(R.id.tv_land) != null) {
            isLand = true;
            manager = new GridLayoutManager(this, 5);
        } else {
            isLand = false;
            manager = new GridLayoutManager(this, 3);
        }
        recyclerView.setLayoutManager(manager);
        mAdapter = new CustomerShowAdapter(this, mData);
        mAdapter.setOnItemClickListener(this);
        recyclerView.setAdapter(mAdapter);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        FileBean item = (FileBean) adapter.getItem(position);
        switch (type) {
            case 0:
                Contants.playBeans = mData;
                startActivity(BrowserPicActivity.createIntent(CustomerShowActivity.this, position));
                break;
            case 1:
                int index = mData.indexOf(item);
                if (playVideoList.size() > 0) {
                    playVideoList.clear();
                }
                for (int i = index; i < mData.size(); i++) {
                    playVideoList.add(mData.get(i));
                }
                Contants.playBeans = playVideoList;
                startActivity(new Intent(this, CustomerVideoPlayActivity.class));

                break;
            case 2:
                File file = new File(item.getFilePath());
                if (file.exists()) {
                    Intent intent = new Intent(CustomerShowActivity.this, OpenLocalBookTest.class);
                    intent.putExtra("pdfPath", file.toString());
                    intent.putExtra("bookTitle", item.getFileName());
                    intent.putExtra("isLand", isLand);
                    startActivity(intent);
                } else {
                    Toast.makeText(CustomerShowActivity.this, "文件没有找到", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private void showDialog() {
        progressDialog.setMessage("加载中...");
        progressDialog.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_image:
                if (type == 0) return;
                type = 0;
                updateMenuStatus();
                initData(Contants.IMAGE, type);
                break;
            case R.id.tv_video:
                if (type == 1) return;
                type = 1;
                updateMenuStatus();
                initData(Contants.VIDEO, type);
                break;
            case R.id.tv_file:
                if (type == 2) return;
                type = 2;
                updateMenuStatus();
                initData(Contants.FILE, type);
                break;
        }
    }

    private void updateMenuStatus() {
        switch (type) {
            case 0:
                status();
                image.setBackgroundColor(Color.WHITE);
                image.setTextColor(getResources().getColor(R.color.green));
                break;
            case 1:
                status();
                video.setBackgroundColor(Color.WHITE);
                video.setTextColor(getResources().getColor(R.color.green));
                break;
            case 2:
                status();
                file.setBackgroundColor(Color.WHITE);
                file.setTextColor(getResources().getColor(R.color.green));
                break;
        }
    }

    private void status() {
        image.setBackgroundColor(getResources().getColor(R.color.background));
        image.setTextColor(getResources().getColor(R.color.black));
        video.setBackgroundColor(getResources().getColor(R.color.background));
        video.setTextColor(getResources().getColor(R.color.black));
        file.setBackgroundColor(getResources().getColor(R.color.background));
        file.setTextColor(getResources().getColor(R.color.black));
    }
}
